//
//  TestTCPConnect.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-16.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "TestTCPConnect.h"
#import "MBProgressController.h"
#import "NetWorkRequestTest.h"


static  NSString *SeviceAddr = nil;
static  NSString *ServerIP = nil;
static  NSString *ServerPORT = nil;

@interface TestTCPConnect()
{
    NSInputStream *inputStream;
    NSOutputStream *outputStream;
}

@end

@implementation TestTCPConnect


+ (TestTCPConnect *)sharedInstance;
{
    static TestTCPConnect *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[TestTCPConnect alloc] init];
    });
    
    return _sharedInstance;
}


- (void)initNetworkCommunication:(NSDictionary *)requestDic
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    SeviceAddr = [requestDic objectForKey:@"dataSeviceAddr"];
    ServerIP = [requestDic objectForKey:@"pushServerIP"];
    ServerPORT = [requestDic objectForKey:@"pushSevicePORT"];
    
    if([SeviceAddr isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"数据服务地址为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    if([ServerIP isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务器IP为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    if([ServerPORT isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务端口为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }

    
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ServerIP, [ServerPORT intValue], &readStream, &writeStream);
    inputStream = (__bridge_transfer NSInputStream *)readStream;
    outputStream = (__bridge_transfer NSOutputStream*)writeStream;
    
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    
    [inputStream open];
    [outputStream open];
}


#pragma -mark
#pragma -mark NSStreamDelegate
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    NSString    *event;
    
    switch (eventCode) {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            break;
        case NSStreamEventHasBytesAvailable:
        {
            event = @"NSStreamEventHasBytesAvailable";
            if(aStream == inputStream)
            {
                NSMutableData   *input = [[NSMutableData alloc] init];
                
                
                uint8_t buffer[1024];
                NSInteger len;
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if(len > 0)
                    {
                        [input appendBytes:buffer length:len];
                    }
                }
                
                NSString    *resultstring = [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding];
                NSLog(@"接收:%@",resultstring);
                [[MBProgressController sharedInstance] showTipsOnlyText:resultstring
                                                               AndDelay:1.5];
                [[MBProgressController sharedInstance] hide];
            }
        }
            break;
        case NSStreamEventHasSpaceAvailable:
            event = @"NSStreamEventHasSpaceAvailable";
            if(aStream == outputStream)
            {
               // isTesttcp = YES;
                //if(isTesttcp && isTesthttp)
                // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[MBProgressController sharedInstance] showTipsOnlyText:@"测试推送服务连接成功!"
                                                               AndDelay:1.5];
                // });
                //sleep(1);
                
            }
            break;
        case NSStreamEventErrorOccurred:
            event = @"NSStreamEventErrorOccurred";
            [[MBProgressController sharedInstance] showTipsOnlyText:@"测试推送服务连接失败"
                                                           AndDelay:1.5];
            // isTesttcp = NO;
            [self close];//自定义的close
            break;
        case NSStreamEventEndEncountered:
            event = @"NSStreamEventEndEncountered";
            [[MBProgressController sharedInstance] showTipsOnlyText:@"与服务器连接中断..."
                                                           AndDelay:1.5];
            NSLog(@"Error:%ld:%@",(long)[[aStream streamError] code],[[aStream streamError] localizedDescription]);
            break;
        default:
            [self close];
            event = @"Unknown";
            [[MBProgressController sharedInstance] showTipsOnlyText:@"测试推送服务连接失败"
                                                           AndDelay:1.5];
           //  isTesttcp = NO;
            break;
    }
    //[NetWorkRequestTest networkTestConnected];
   // sleep(1);

    NSLog(@"event--%@",event);
}

-(void)close
{
    [outputStream close];
    [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream setDelegate:nil];
    [inputStream close];
    [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream setDelegate:nil];
}



@end
